package top.infopub.mgr.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

@SuppressWarnings("deprecation")
public class HttpClientUtil {
	public static final String httpClientGet(String url) {
		String result = null;
		HttpClient client = new HttpClient();
		if (url.startsWith("https")) {
//			System.out.println("忽略https设置......");
			Protocol myhttps = new Protocol("https",
					new MySecureProtocolSocketFactory(), 443);
			Protocol.registerProtocol("https", myhttps);
			client.getParams().setBooleanParameter(
					"http.protocol.expect-continue", false);
		}
		GetMethod getMethod = new GetMethod(url);
		try {
			client.executeMethod(getMethod);
			String responseCharSet = getMethod.getResponseCharSet();
			byte[] responseBody = getMethod.getResponseBody();
			// result = getMethod.getResponseBodyAsString();
			result = new String(responseBody, responseCharSet);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			getMethod.releaseConnection();
		}
		return result;
	}

	public static final String httpClientGet(String url,
			ArrayList<NameValuePair> list) {
		String result = "";
		HttpClient client = new HttpClient();
		if (url.startsWith("https")) {
//			System.out.println("忽略https设置......");
			Protocol myhttps = new Protocol("https",
					new MySecureProtocolSocketFactory(), 443);
			Protocol.registerProtocol("https", myhttps);
			client.getParams().setBooleanParameter(
					"http.protocol.expect-continue", false);
		}
		GetMethod getMethod = new GetMethod(url);
		try {
			NameValuePair[] params = new NameValuePair[list.size()];
			for (int i = 0; i < list.size(); i++) {
				params[i] = list.get(i);
			}
			getMethod.setQueryString(params);
			client.executeMethod(getMethod);
			String responseCharSet = getMethod.getResponseCharSet();
			byte[] responseBody = getMethod.getResponseBody();
			// result = getMethod.getResponseBodyAsString();
			result = new String(responseBody, responseCharSet);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			getMethod.releaseConnection();
		}
		return result;
	}

	public static final String httpClientPost(String url,
			ArrayList<NameValuePair> list) {
		String result = "";
		HttpClient client = new HttpClient();
		if (url.startsWith("https")) {
//			System.out.println("忽略https设置......");
			Protocol myhttps = new Protocol("https",
					new MySecureProtocolSocketFactory(), 443);
			Protocol.registerProtocol("https", myhttps);
			client.getParams().setBooleanParameter(
					"http.protocol.expect-continue", false);
		}
		PostMethod postMethod = new PostMethod(url);
		try {
			NameValuePair[] params = new NameValuePair[list.size()];
			for (int i = 0; i < list.size(); i++) {
				params[i] = list.get(i);
			}
			postMethod.addParameters(params);
			client.executeMethod(postMethod);
			result = postMethod.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();
		}
		return result;
	}

	public static final String postBody(String url, String body) {
		String result = "";
		HttpClient client = new HttpClient();
		if (url.startsWith("https")) {
//			System.out.println("忽略https设置......");
			Protocol myhttps = new Protocol("https",
					new MySecureProtocolSocketFactory(), 443);
			Protocol.registerProtocol("https", myhttps);
			client.getParams().setBooleanParameter(
					"http.protocol.expect-continue", false);
		}
		PostMethod postMethod = new PostMethod(url);
		try {
			postMethod.getParams().setParameter(
					HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
			postMethod.setRequestBody(body);
			client.executeMethod(postMethod);
			result = postMethod.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();
		}
		return result;
	}
	
	public static final String postJson(String url, String body) {
		String result = "";
		HttpClient client = new HttpClient();
		if (url.startsWith("https")) {
//			System.out.println("忽略https设置......");
			Protocol myhttps = new Protocol("https",
					new MySecureProtocolSocketFactory(), 443);
			Protocol.registerProtocol("https", myhttps);
			client.getParams().setBooleanParameter(
					"http.protocol.expect-continue", false);
		}
		client.getParams().setContentCharset("UTF-8");
		client.getParams().setHttpElementCharset("UTF-8");
		client.getHttpConnectionManager().getParams()
				.setConnectionTimeout(30000);
		client.getHttpConnectionManager().getParams().setSoTimeout(30000);
		PostMethod postMethod = new PostMethod(url);
		try {
			postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
			postMethod.setRequestBody(body);
			client.executeMethod(postMethod);
			result = postMethod.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();
		}
		return result;
	}
	
	public static final String putJson(String url, String body) {
		String result = "";
		CloseableHttpClient client = HttpClients.createDefault();
		if (url.startsWith("https")) {
//			System.out.println("忽略https设置......");
			Protocol myhttps = new Protocol("https",
					new MySecureProtocolSocketFactory(), 443);
			Protocol.registerProtocol("https", myhttps);
			client.getParams().setBooleanParameter(
					"http.protocol.expect-continue", false);
		}
		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectTimeout(5000)
				.setConnectionRequestTimeout(5000)
				.setRedirectsEnabled(true)
				.build();
		HttpPut httpPut = new HttpPut(url);
		try {
			httpPut.setConfig(requestConfig);
			httpPut.addHeader("Content-Type", "application/json");
			StringEntity entity = new StringEntity(body, "utf-8");
			entity.setContentEncoding("utf-8");
			entity.setContentType("application/json");
			httpPut.setEntity(entity);
			CloseableHttpResponse closeableHttpResponse = client.execute(httpPut);
			if (null != closeableHttpResponse && !"".equals(closeableHttpResponse)) {
				if (closeableHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					HttpEntity httpEntity = closeableHttpResponse.getEntity();
					result = EntityUtils.toString(httpEntity);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpPut.releaseConnection();
		}
		return result;
	}

	/**
	 * HttpClientGet远程接口调用
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static String httpClientGet(String url, Map<String, String> header,
			Map<String, String> params) {
		GetMethod method = null;
		try {
			HttpClient client = new HttpClient();
			if (url.startsWith("https")) {
//				System.out.println("忽略https设置......");
				Protocol myhttps = new Protocol("https",
						new MySecureProtocolSocketFactory(), 443);
				Protocol.registerProtocol("https", myhttps);
				client.getParams().setBooleanParameter(
						"http.protocol.expect-continue", false);
			}
			client.getParams().setContentCharset("UTF-8");
			client.getParams().setHttpElementCharset("UTF-8");
			client.getHttpConnectionManager().getParams()
					.setConnectionTimeout(30000);
			client.getHttpConnectionManager().getParams().setSoTimeout(30000);
			method = getGetMethod(url, header, params);
			client.executeMethod(method);
			String res = method.getResponseBodyAsString();
			method.releaseConnection();
			return res;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (method != null)
				method.releaseConnection();
		}
		return null;
	}

	/**
	 * HttpClientPost远程接口调用
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static String httpClientPost(String url, Map<String, String> header,
			Map<String, String> params) {
		PostMethod method = null;
		try {
			HttpClient client = new HttpClient();
			if (url.startsWith("https")) {
//				System.out.println("忽略https设置......");
				Protocol myhttps = new Protocol("https",
						new MySecureProtocolSocketFactory(), 443);
				Protocol.registerProtocol("https", myhttps);
				client.getParams().setBooleanParameter(
						"http.protocol.expect-continue", false);
			}
			client.getParams().setContentCharset("UTF-8");
			client.getParams().setHttpElementCharset("UTF-8");
			client.getHttpConnectionManager().getParams()
					.setConnectionTimeout(30000);
			client.getHttpConnectionManager().getParams().setSoTimeout(30000);
			method = getPostMethod(url, header, params);
			client.executeMethod(method);
			String res = method.getResponseBodyAsString();
			return res;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (method != null)
				method.releaseConnection();
		}
		return null;
	}

	@SuppressWarnings("rawtypes")
	private static GetMethod getGetMethod(String url,
			Map<String, String> header, Map<String, String> params) {
		GetMethod get = new GetMethod(url);
		try {
			if (header != null && header.size() > 0) {
				Iterator iterator = header.entrySet().iterator();
				while (iterator.hasNext()) {
					Map.Entry entry = (Map.Entry) iterator.next();
					Object key = entry.getKey();
					Object val = entry.getValue();
					if (key == null || key.toString().trim().length() == 0
							|| val == null
							|| val.toString().trim().length() == 0)
						continue;
					String headerName = key.toString();
					String headerValue = val.toString();
					get.addRequestHeader(headerName, headerValue);
				}
			}
			if (params != null && params.size() > 0) {
				NameValuePair[] nameVals = new NameValuePair[params.size()];
				Iterator iterator = params.entrySet().iterator();
				int i = 0;
				while (iterator.hasNext()) {
					Map.Entry entry = (Map.Entry) iterator.next();
					Object key = entry.getKey();
					Object val = entry.getValue();
					if (key == null || key.toString().trim().length() == 0
							|| val == null
							|| val.toString().trim().length() == 0)
						continue;
					String paramName = key.toString();
					String paramValue = val.toString();
					NameValuePair nameVal = new NameValuePair(paramName,
							paramValue);
					nameVals[i] = nameVal;
					i++;
				}
				get.setQueryString(nameVals);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return get;
	}

	@SuppressWarnings("rawtypes")
	private static PostMethod getPostMethod(String url,
			Map<String, String> header, Map<String, String> params) {
		PostMethod post = new PostMethod(url);
		try {
			if (header != null && header.size() > 0) {
				Iterator iterator = header.entrySet().iterator();
				while (iterator.hasNext()) {
					Map.Entry entry = (Map.Entry) iterator.next();
					Object key = entry.getKey();
					Object val = entry.getValue();
					if (key == null || key.toString().trim().length() == 0
							|| val == null
							|| val.toString().trim().length() == 0)
						continue;
					String headerName = key.toString();
					String headerValue = val.toString();
					post.addRequestHeader(headerName, headerValue);
				}
			}
			if (params != null && params.size() > 0) {
				Iterator iterator = params.entrySet().iterator();
				while (iterator.hasNext()) {
					Map.Entry entry = (Map.Entry) iterator.next();
					Object key = entry.getKey();
					Object val = entry.getValue();
					if (key == null || key.toString().trim().length() == 0
							|| val == null
							|| val.toString().trim().length() == 0)
						continue;
					String paramName = key.toString();
					String paramValue = val.toString();
					post.addParameter(paramName, paramValue);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return post;
	}
	
	public static byte[] getNetImgBytes(String imgUrl) {
		ByteArrayOutputStream data = new ByteArrayOutputStream();
		try {
			URL url = new URL(imgUrl);
			byte[] bytes = new byte[1024];
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			InputStream is = conn.getInputStream();
			int len = -1;
			while ((len = is.read(bytes)) != -1) {
				data.write(bytes, 0, len);
			}
			is.close();
			return data.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		System.out.println(HttpClientUtil.httpClientGet("http://admin.jollychic.com/ssop/basic/uploadWithdrawFile.htm"));
	}
}
